from PyQt5.QtCore import pyqtSignal, pyqtSlot, QModelIndex
from PyQt5.QtWidgets import QListView,\
                            QMenu,\
                            QMessageBox

from RBK.View.AddDialog import AddDialog
from RBK.View.RemoveDialog import RemoveDialog

class List (QListView):
    dataTypeAdded = pyqtSignal(str)
    dataTypeRemoved = pyqtSignal(str)
    resetTableView = pyqtSignal(QModelIndex, int)

    InputDataMode = 1
    EditDataTypeMode = 2

    def __init__(self):
        super().__init__()
        self.mode = self.InputDataMode
        self.core = False

    # Only display context menu if this is a core rulebook.
    # Non-core rulebooks should not be able to modify structure or add datatypes
    def contextMenuEvent(self, event):
        if(self.core):
            m = QMenu()
            m.addAction('Add DataType', self.loadAddDTDialog)
            index = self.indexAt(event.pos())
            dt = index.data()
            if(index.isValid()):
                m.addAction('Remove DataType {0}'.format(dt), self.loadRemoveDTDialog)
            m.addSeparator()
            if(self.mode == self.InputDataMode):
                m.addAction('Switch to Edit DataTypes mode', self.switchToEditDataTypeMode)
            elif (self.mode == self.EditDataTypeMode):
                m.addAction('Switch to Input Data mode', self.switchToInputDataMode)
            else:       # This condition should never happen.
                print('Error in List.contextMenuEvent')

            event.accept()
            m.exec(event.globalPos())


    def currentChanged(self, new, old):
        self.current = new
        self.resetTableView.emit(self.current, self.mode)


    def loadAddDTDialog(self):
        adt = AddDialog(self, self.model())
        adt.added.connect(self.addDataType)
        adt.exec()


    def loadRemoveDTDialog(self):
        datatype = self.selectedIndexes()[0].data()

        rdt = RemoveDialog(self, self.model(), datatype)
        rdt.removed.connect(self.removeDataType)
        rdt.exec()


    def setCore(self, core):
        self.core = core

    # typename is ignored, since for the list this will always be 'DataType'.
    # This value is used by the Tables.
    @pyqtSlot(str, str)
    def addDataType(self, typename, text):
        self.dataTypeAdded.emit(text)


    # typename is ignored, since for the list this will always be 'DataType'.
    # This value is used by the Tables.
    @pyqtSlot(str, str)
    def removeDataType(self, typename, datatype):
        row = self.selectedIndexes()[0].row()

        index = self.model().index(row-1, 0)
        self.dataTypeRemoved.emit(datatype)
        self.setCurrentIndex(index)

    @pyqtSlot()
    def switchToEditDataTypeMode(self):
        self.mode = self.EditDataTypeMode
        self.resetTableView.emit(self.current, self.mode)


    @pyqtSlot()
    def switchToInputDataMode(self):
        self.mode = self.InputDataMode
        self.resetTableView.emit(self.current, self.mode)
